package webuser

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"goweb-goframe/internal/dao"
	"goweb-goframe/internal/model"
	"goweb-goframe/internal/model/entity"
	"goweb-goframe/internal/packed"
)

func (s sWebUser) Login(ctx context.Context, req *model.WebUserLoginReq) (res string, err error) {
	db := dao.TbAccount.Ctx(ctx)
	var TbAccount *entity.TbAccount
	err = db.Where(g.Map{
		"phone_number": &req.PhoneNumber,
	}).Scan(&TbAccount)

	// 账号是否存在
	if err != nil {
		err = packed.Err.Skip(20100)
		return "", err
	}

	// 校验密码
	var validate = ValidPass(req.Password, TbAccount)
	if !validate {
		err = packed.Err.Skip(20100)
		return "", err
	}

	// 校验企业账号状态
	if TbAccount.Status == 0 {
		err = packed.Err.Skip(20104)
		return "", err
	}

	// 账号密码正确，企业状态正常后，返回token的同时，记录登录时间和登录IP
	res, _ = packed.MakeToken(TbAccount.Id) // 根据用户ID生成token

	// 记录登录时间
	_, err = db.Data(g.Map{
		"login_time": gtime.Now(),
	}).Where(TbAccount.Id).Update()
	return res, err
}
